package czk.concrent.threadpool.method;

import java.util.Arrays;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * invokeAny的demo
 * 返回最先执行完毕的那个线程结果
 * @Author:ChenZhangKun
 * @Date: 2020/7/5 17:29
 */
@SuppressWarnings("all")
public class InvokeAny {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 创建线程数
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        // 执行任务，利用lambda表达式计算
        // 接收线程的集合
        String s = executorService.invokeAny(Arrays.asList(
                () -> {
                    System.out.println("第一个任务开始了");
                    Thread.sleep(1 * 1000);
                    return "1";
                },

                () -> {
                    System.out.println("第二个任务开始了");
                    Thread.sleep(1 * 500);
                    return "2";
                },
                () -> {
                    System.out.println("第三个任务开始了");
                    Thread.sleep(3 * 1000);
                    return "3";
                }
        ));
        System.out.println(s);
    }
}
